import {
  PlusOutlined,
  DeleteOutlined,
  CloudDownloadOutlined,
  CloudUploadOutlined,
  SyncOutlined,
  LockOutlined,
  UnlockOutlined,
} from '@ant-design/icons';
import { Button, Checkbox, Col, Popconfirm, Row, message } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { getUserRoles, grantRoles, pageUser } from '@/services/system/user';
import type { UserItem, UserParams } from '@/services/system/types';
import {
  ProFormText,
  ProFormDatePicker,
  ProFormRadio,
  ProFormSelect,
  ModalForm,
} from '@ant-design/pro-form';
import EditForm from '@/components/EditForm';
import { getDictValues } from '@/services/system/dictValue';
import DeptTree from '@/components/DeptTree';
import { UserColumns } from './columns';
import { handleAdd, handleUpdate, handleRemove, handleResetPwd } from './action';

import { listRole } from '@/services/system/role';
import type { CheckboxValueType } from 'antd/lib/checkbox/Group';
import SzhomeTable from '@/components/Custom/SzhomeTable';
import { treeDept } from '@/services/system/dept';

const roles = await listRole({});
const statusList = await getDictValues('user.status', true);
const genders = await getDictValues('gender', true);

const depts = await treeDept({});
console.log(depts);

const User: React.FC = () => {
  /** 新建窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<UserItem>();
  const [selectedRowsState, setSelectedRows] = useState<UserItem[]>([]);

  const [userRolesVisible, setUserRolesVisible] = useState<boolean>(false);
  const [selectedRoles, setSelectedRoles] = useState<number[] | string[]>([]);

  const columns: ProColumns<UserItem>[] = [
    ...UserColumns,
    {
      title: '操作',
      align: 'center',
      dataIndex: 'option',
      valueType: 'option',
      width: 160,
      render: (_, record) => [
        <a
          key={'edit-' + record.id}
          onClick={() => {
            setCurrentRow(record);
            handleModalVisible(true);
          }}
        >
          编辑
        </a>,
        <a
          key="role"
          onClick={() => {
            getUserRoles(record.id).then((res) => {
              setSelectedRoles(res.data);
              setUserRolesVisible(true);
              setCurrentRow(record);
            });
          }}
        >
          角色
        </a>,
        <Popconfirm
          key={'delete-' + record.id}
          title="您确定要删除此用户吗？"
          onConfirm={async () => {
            await handleRemove([record]);
            setSelectedRows([]);
            actionRef.current?.reloadAndRest?.();
          }}
          okText="Yes"
          cancelText="No"
        >
          <a key="remove">删除</a>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <PageContainer>
      <SzhomeTable<UserItem, UserParams>
        actionRef={actionRef}
        request={pageUser}
        columns={columns}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setCurrentRow(undefined);
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新增
          </Button>,

          <Button
            key="primary"
            disabled={selectedRowsState?.length == 0}
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <UnlockOutlined /> 解封
          </Button>,

          <Button
            key="primary"
            disabled={selectedRowsState?.length == 0}
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <LockOutlined /> 锁定
          </Button>,

          <Button
            key="primary"
            disabled={selectedRowsState?.length == 0}
            onClick={() => {
              handleResetPwd(selectedRowsState);
            }}
          >
            <SyncOutlined /> 重置密码
          </Button>,

          <Popconfirm
            key={'batch_remove'}
            disabled={selectedRowsState?.length == 0}
            title={'您确定要删除已选' + selectedRowsState?.length + '条数据吗？'}
            onConfirm={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
            okText="Yes"
            cancelText="No"
          >
            <Button key="batch_remove" danger disabled={selectedRowsState?.length == 0}>
              <DeleteOutlined />
              删除
            </Button>
          </Popconfirm>,

          <Button
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <CloudDownloadOutlined /> 导出
          </Button>,

          <Button
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <CloudUploadOutlined /> 导入
          </Button>,
        ]}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />

      <EditForm
        visible={createModalVisible}
        name="用户"
        model={currentRow || { id: undefined }}
        onAdd={handleAdd}
        onUpdate={handleUpdate}
        afterEdit={() => {
          setCurrentRow(undefined);

          if (actionRef.current) {
            actionRef.current.reload();
          }
        }}
        onCancel={handleModalVisible}
      >
        <ProFormText name="id" hidden={true} />
        <DeptTree title="部门" name="deptId" required cols={12} />
        <ProFormSelect
          required
          label="状态"
          name="status"
          valueEnum={statusList}
          colProps={{ span: 12 }}
        />
        <ProFormText required label="账号" name="username" colProps={{ xs: 12 }} />
        <ProFormText required label="姓名" name="realName" colProps={{ xs: 12 }} />
        <ProFormText label="邮箱" name="email" colProps={{ xs: 12 }} />
        <ProFormText label="手机" name="phone" colProps={{ xs: 12 }} />
        <ProFormDatePicker label="生日" name="birthday" colProps={{ xs: 12 }} width="lg" />
        <ProFormRadio.Group label="性别" name="gender" colProps={{ xs: 12 }} valueEnum={genders} />
      </EditForm>

      <ModalForm
        title="分配角色"
        visible={userRolesVisible}
        onVisibleChange={(visible) => {
          setUserRolesVisible(visible);
          if (!visible) {
            setCurrentRow(undefined);
            setSelectedRoles([]);
          }
        }}
        width={600}
        modalProps={{
          destroyOnClose: true,
        }}
        onFinish={async () => {
          const res = await grantRoles(currentRow?.id || 0, selectedRoles);
          if (res.success) {
            message.success('用户角色分配成功');
          } else {
            message.error('用户角色分配失败');
          }
          return res.success;
        }}
      >
        <Checkbox.Group
          style={{ width: '100%' }}
          value={selectedRoles}
          onChange={(checkedValues: CheckboxValueType[]) => {
            setSelectedRoles(checkedValues.map((val) => val.toString()));
          }}
        >
          <Row gutter={[10, 10]}>
            {roles.data.map((o) => {
              return (
                <Col span={8} key={o.id}>
                  <Checkbox key={o.id} value={o.id.toString()} name="roleIds">
                    {o.name}
                  </Checkbox>
                </Col>
              );
            })}
          </Row>
        </Checkbox.Group>
      </ModalForm>
    </PageContainer>
  );
};

export default User;
